package com.wh.springboot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.springboot.common.entity.XueYuan;
import com.wh.springboot.service.IUserService;
import com.wh.springboot.service.IXueYuanService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import com.wh.springboot.common.Result;

import java.util.List;

import com.wh.springboot.service.IBanJiService;
import com.wh.springboot.common.entity.BanJi;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author elsy
 * @since 2023-04-15
 */
@RestController
@RequestMapping("/banji")
public class BanJiController {
    @Resource
    private IBanJiService banJiService;

    @Resource
    private IUserService userService;

    @Resource
    private IXueYuanService xueYuanService;

    // 新增和修改
    @PostMapping
    public Result save(@RequestBody BanJi banJi) {
        //新增或者更新
        return Result.success(banJiService.saveOrUpdate(banJi));
    }

    //  查询所有数据
    @GetMapping
    public Result findAll() {
        return Result.success(banJiService.list());
    }

    //根据id查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(banJiService.getById(id));
    }

    //删除数据
    @DeleteMapping("/{id}")//id 与下面的id必须一致
    //    @PathVariable 表示 url 这个参数
    public Result delete(@PathVariable Integer id) {
        return Result.success(banJiService.removeById(id));
    }

    //批量删除
    @DeleteMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(banJiService.removeByIds(ids));
    }

    //分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name
    ) {
//        QueryWrapper<BanJi> queryWrapper = new QueryWrapper<>();
//        //输入的值是非空的话，再执行
//        if (!"".equals(name)) {
//            queryWrapper.like("name", name);
//        }
//        queryWrapper.orderByDesc("id");
//        Page<BanJi> page = banJiService.page(new Page<>(pageNum, pageSize), queryWrapper);
//        List<BanJi> records = page.getRecords();
//        for (BanJi record : records) {
//            User user = userService.getById(record.getTeacherId());
//            if (user != null) {
//                record.setTeacher(user.getNickname());
//            }
//
//        }
        Page<BanJi> page = banJiService.findPage(new Page<>(pageNum, pageSize), name);
        for (BanJi banJi : page.getRecords()) {
            if (banJi.getXueYuanId() != null) {
                //班級学院XueYuanservice查库
                XueYuan xueYuan = xueYuanService.getById(banJi.getXueYuanId());
                banJi.setAcademy(xueYuan.getName());
            }
        }
        return Result.success(page);
    }
}

